package com.ailanyin.security.utils;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.jwt.JWTPayload;
import cn.hutool.jwt.JWTUtil;

import java.util.HashMap;
import java.util.Map;

/**
 * @author ailanyin
 * @version 1.0
 * @since 2022/6/8 0008 上午 11:44
 */
public class TokenUtil {

    /**
     * jwt 加解密密钥,第一次项目启动时创建随机数
     */
    public static String secret;

    public static String generateToken(String username) {
        DateTime now = DateTime.now();
        // 3天过期
        DateTime newTime = now.offsetNew(DateField.HOUR, 72);

        Map<String, Object> payload = new HashMap<String, Object>(4);
        //签发时间
        payload.put(JWTPayload.ISSUED_AT, now);
        //过期时间
        payload.put(JWTPayload.EXPIRES_AT, newTime);
        //生效时间
        payload.put(JWTPayload.NOT_BEFORE, now);
        //载荷
        payload.put(JWTPayload.SUBJECT, username);

        return JWTUtil.createToken(payload, secret.getBytes());
    }

    public static String getUserNameFromToken(String token) {
        try {
            return JWTUtil.parseToken(token).getPayload(JWTPayload.SUBJECT).toString();
        } catch (Exception e) {
            return null;
        }
    }

    public static boolean validateToken(String token) {
        try {
            if (!JWTUtil.verify(token, secret.getBytes())) {
                return false;
            }
            long expireTime = Long.parseLong(JWTUtil.parseToken(token).getPayload(JWTPayload.EXPIRES_AT).toString() + "000");
            return new DateTime(expireTime).after(DateTime.now());
        } catch (NumberFormatException e) {
            return false;
        }
    }
}
